package cn.edu.jsu.zjj.model.utils;

import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;

public class OtherUtils {
    public static int getFilledFieldsCount(Object obj) {
        if (obj == null) {
            return 0;
        }

        int filledFieldsCount = 0;
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true); // 允许访问私有字段
            try {
                Object value = field.get(obj);
                if (value != null) {
                    filledFieldsCount++;
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return filledFieldsCount;
    }

    public static LocalDate transformStringToLocalDate(String date) {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
        if (date == null || date.isEmpty()) {
            return null;
        }
        try {
            return LocalDate.parse(date, formatter);
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("Invalid date format for LocalDate: " + date, e);
        }
    }

    public static LocalDateTime transformStringToLocalDateTime(String dateTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        if (dateTime == null || dateTime.isEmpty()) {
            return null;
        }
        try {
            return LocalDateTime.parse(dateTime, formatter);
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("Invalid date format for LocalDateTime: " + dateTime, e);
        }
    }

    public static Date transformStringToDate(String date) {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
        if (date == null || date.isEmpty()) {
            return null;
        }
        try {
            LocalDate localDate = LocalDate.parse(date, formatter);
            return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("Invalid date format for Date: " + date, e);
        }
    }


    public static LocalDate transform(String date) {
        if (date == null || date.isEmpty()) {
            return null;
        }
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
            LocalDateTime localDateTime = LocalDateTime.parse(date, formatter);
            return localDateTime.toLocalDate();
    }

}
